// 标签页编辑器组件
// 集成Monaco Editor实例管理，支持多文件编辑

import React, { useEffect, useRef, useCallback, useState } from 'react';
import { useTabStore } from '../stores/tabStore';
import { getEditorInstanceManager, EditorInstance } from '../services/editorInstanceManager';
import { cn } from '../utils/cn';

// 编辑器组件属性
interface TabEditorProps {
  className?: string;
  onContentChange?: (tabId: string, content: string) => void;
  onCursorPositionChange?: (tabId: string, line: number, column: number) => void;
  onSelectionChange?: (tabId: string, selection: any) => void;
}

// 标签页编辑器组件
export const TabEditor: React.FC<TabEditorProps> = ({
  className,
  onContentChange,
  onCursorPositionChange,
  onSelectionChange,
}) => {
  const {
    tabs,
    activeTabId,
    updateTabContent,
    updateTabStatus,
    updateTabPosition,
    updateTabSelection,
    updateTabScrollPosition,
  } = useTabStore();

  const containerRef = useRef<HTMLDivElement>(null);
  const editorManagerRef = useRef(getEditorInstanceManager());
  const [currentInstance, setCurrentInstance] = useState<EditorInstance | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  // 初始化编辑器管理器
  useEffect(() => {
    const manager = editorManagerRef.current;
    
    if (containerRef.current) {
      manager.setContainer(containerRef.current);
    }

    // 设置事件监听器
    manager.notifyContentChange = (instance, content) => {
      updateTabContent(instance.tabId, content);
      onContentChange?.(instance.tabId, content);
    };

    manager.notifyCursorPositionChange = (instance, position) => {
      updateTabPosition(instance.tabId, {
        line: position.lineNumber,
        column: position.column,
      });
      onCursorPositionChange?.(instance.tabId, position.lineNumber, position.column);
    };

    manager.notifySelectionChange = (instance, selection) => {
      updateTabSelection(instance.tabId, {
        start: {
          line: selection.startLineNumber,
          column: selection.startColumn,
        },
        end: {
          line: selection.endLineNumber,
          column: selection.endColumn,
        },
      });
      onSelectionChange?.(instance.tabId, selection);
    };

    manager.notifyScrollChange = (instance, scrollTop, scrollLeft) => {
      updateTabScrollPosition(instance.tabId, {
        top: scrollTop,
        left: scrollLeft,
      });
    };

    return () => {
      // 清理资源
      manager.destroy();
    };
  }, []);

  // 处理活动标签页变化
  useEffect(() => {
    const loadActiveTab = async () => {
      if (!activeTabId || !containerRef.current) {
        setCurrentInstance(null);
        return;
      }

      const tab = tabs.get(activeTabId);
      if (!tab) {
        setCurrentInstance(null);
        return;
      }

      setIsLoading(true);

      try {
        const manager = editorManagerRef.current;
        
        // 获取或创建编辑器实例
        const instance = await manager.getOrCreateInstance(tab);
        
        // 激活实例
        const activeInstance = manager.activateInstance(activeTabId);
        
        if (activeInstance) {
          setCurrentInstance(activeInstance);
          
          // 恢复编辑器状态
          restoreEditorState(activeInstance, tab);
        }
      } catch (error) {
        console.error('Failed to load editor instance:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadActiveTab();
  }, [activeTabId, tabs]);

  // 恢复编辑器状态
  const restoreEditorState = useCallback((instance: EditorInstance, tab: any) => {
    const { editor } = instance;

    // 恢复光标位置
    if (tab.cursorPosition) {
      editor.setPosition({
        lineNumber: tab.cursorPosition.line,
        column: tab.cursorPosition.column,
      });
    }

    // 恢复选择范围
    if (tab.selection) {
      editor.setSelection({
        startLineNumber: tab.selection.start.line,
        startColumn: tab.selection.start.column,
        endLineNumber: tab.selection.end.line,
        endColumn: tab.selection.end.column,
      });
    }

    // 恢复滚动位置
    if (tab.scrollPosition) {
      editor.setScrollTop(tab.scrollPosition.top);
      editor.setScrollLeft(tab.scrollPosition.left);
    }

    // 聚焦编辑器
    editor.focus();
  }, []);

  // 处理标签页内容更新
  useEffect(() => {
    if (!activeTabId || !currentInstance) return;

    const tab = tabs.get(activeTabId);
    if (!tab) return;

    const manager = editorManagerRef.current;
    
    // 更新编辑器内容
    if (currentInstance.model.getValue() !== tab.content) {
      manager.updateInstanceContent(activeTabId, tab.content);
    }

    // 更新编辑器语言
    if (currentInstance.language !== tab.language) {
      manager.updateInstanceLanguage(activeTabId, tab.language);
    }
  }, [activeTabId, currentInstance, tabs]);

  // 获取编辑器统计信息
  const getEditorStats = useCallback(() => {
    const manager = editorManagerRef.current;
    const instances = manager.getAllInstances();
    const totalMemory = manager.getTotalMemoryUsage();

    return {
      instanceCount: instances.length,
      totalMemory: totalMemory.toFixed(2),
      activeInstance: currentInstance?.id || 'None',
    };
  }, [currentInstance]);

  return (
    <div className={cn('relative flex flex-col h-full', className)}>
      {/* 编辑器容器 */}
      <div
        ref={containerRef}
        className="flex-1 relative overflow-hidden"
        style={{ minHeight: '200px' }}
      >
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-gray-100 dark:bg-gray-800 z-10">
            <div className="flex items-center space-x-2">
              <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
              <span className="text-sm text-gray-600 dark:text-gray-400">
                加载编辑器...
              </span>
            </div>
          </div>
        )}

        {!activeTabId && !isLoading && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-center">
              <div className="text-6xl mb-4">📝</div>
              <h3 className="text-xl font-semibold text-gray-700 dark:text-gray-300 mb-2">
                没有打开的文件
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                从左侧文件管理器中选择文件开始编辑
              </p>
            </div>
          </div>
        )}
      </div>

      {/* 调试信息（开发模式） */}
      {process.env.NODE_ENV === 'development' && currentInstance && (
        <div className="absolute bottom-2 right-2 bg-black bg-opacity-75 text-white text-xs p-2 rounded">
          <div>实例: {currentInstance.id}</div>
          <div>内存: {currentInstance.memoryUsage.toFixed(2)}MB</div>
          <div>语言: {currentInstance.language}</div>
          <div>最后使用: {new Date(currentInstance.lastUsed).toLocaleTimeString()}</div>
        </div>
      )}
    </div>
  );
};
